﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using AgFx;
using DepSoft.Mobile.WP7.FollwIt.Framework;
using DepSoft.Mobile.WP7.FollwIt.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DepSoft.Mobile.WP7.FollwIt.ViewModel
{
    /// <summary>
    /// We cache a Movie Collection for 1 hour ( 3600 secs )
    /// We do a cache then refresh, because this will give us following principle
    /// 1. App will make request, [A, B, C] will be returned from cache and displayed
    /// 2. AgFx will see that the cache is no longer valid (more than 3600 seconds have elapsed) and will kick off a new request
    /// 3. Server will return, say [C, D, E]
    /// 4. Cache will be replaced and UI will bind to new value 
    /// </summary>
    [CachePolicy(CachePolicy.CacheThenRefresh, 3600)]
    public class agfxMovieCollectionViewModel : ModelItemBase<MovieCollectionLoadContext>
    {
        #region Public bindable properties
        public const string MoviesPropertyName = "Movies";
        private BatchObservableCollection<Movie> _movies = new BatchObservableCollection<Movie>();

        public ObservableCollection<Movie> Movies
        {
            get
            {
                return _movies;
            }
            set
            {
                if (!ReferenceEquals(_movies, null))
                {
                    _movies.Clear();

                    if (_movies != value)
                    {
                        foreach (var movie in value)
                        {
                            _movies.Add(movie);
                        }
                    }
                }
                RaisePropertyChanged(MoviesPropertyName);
            }
        }
        #endregion

        #region Constructor
        public agfxMovieCollectionViewModel()
        {

        }

        public agfxMovieCollectionViewModel(string userName) : base(new MovieCollectionLoadContext(userName))
        {

        }
        #endregion

        #region AgFx DataLoader
        public class agfxMovieCollectionViewModelLoader : IDataLoader<MovieCollectionLoadContext>
        {
            #region IDataLoader implementation
            public object Deserialize(MovieCollectionLoadContext loadContext, Type objectType, Stream stream)
            {
                agfxMovieCollectionViewModel viewModel = new agfxMovieCollectionViewModel(loadContext.UserName);
                var sr = new StreamReader(stream);
                var movieCollectionJSON = sr.ReadToEnd();
                try
                {
                    JArray movieCollection = JArray.Parse(movieCollectionJSON);

                    JsonSerializer serializer = new JsonSerializer();
                    foreach (JToken movieJSON in movieCollection)
                    {
                        Movie movie = (Movie)serializer.Deserialize(new JTokenReader(movieJSON), typeof(Movie));

                        viewModel.Movies.Add(movie);
                    }
                }
                catch (Exception e)
                {
                    //JObject errorParsed = JObject.Parse(movieCollectionJSON);
                    //throw new MovieLoadException(string.Concat("Error while loading Movie Collection", Environment.NewLine, "Reason: ", errorParsed["message"]));

                    if(!ReferenceEquals(movieCollectionJSON, null))
                        throw new MovieLoadException(string.Concat("Error while loading Movie Collection", Environment.NewLine, movieCollectionJSON), e);
                    else
                        throw new MovieLoadException("Error while loading Movie Collection", e);
                }

                return viewModel;
            }

            public LoadRequest GetLoadRequest(MovieCollectionLoadContext loadContext, Type objectType)
            {
                return new WebLoadRequest(loadContext, new Uri(FollwItApi.GetInstance().GetActionRestURI(RestAction.GetMovieCollection, loadContext.UserName)));
            }
            #endregion
        }
        #endregion
    }
}